#include<iostream>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<string>
#include<cstdlib>
#include<cerrno>
#include<cstring>
#include<unistd.h>

#define MODE 0666

const std::string path = "./sharedM.cpp";
const int proj_id = 0Xffff4332;



int main()
{
  //获取唯一key
  key_t key = ftok(path.c_str(), proj_id);
  if (key == -1)
  { 
    exit(-1);
  }

  //创建共享内存
  int shmid = shmget(key, 4096, IPC_EXCL | IPC_CREAT | MODE);
  if (shmid == -1)
  { 
    exit(-1);
  }

  //挂接
  char* shmadder = (char*)shmat(shmid, nullptr, 0);
  if (shmadder == nullptr)
  {
    std::cout << "nullptr" << std::endl;
    exit(-1);
  }
  
  //开始通信
  
  while (true)
  {
     if (*shmadder != '\0')
     {
       std::cout << "client:   " << shmadder << std::endl;
       shmadder[0] = '\0';
     }
     else 
     {
       sleep(1);
     }
     if (strcmp(shmadder, "nullptr") == 0)
     {
       shmadder[0] = '\0';
       break;
     }
  }

  //去挂接
  int c = shmdt(shmadder);
  if (c == -1)
  {
    exit(-1);
  }

  //释放共享内存
  int n = shmctl(shmid, IPC_RMID, nullptr);
  if (n == -1)
  {
    exit(-1);
  }


  return 0;
}
